package com.ctgu.demo.controller;

import com.ctgu.demo.utils.ApiResult;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/opsForValue")
public class OpsForValueController {

    private final RedisTemplate<String, Object> redisTemplate;

    public OpsForValueController(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    private static final String SESSION_KEY = "ctgu:session:1001";
    private static final String CAPTCHA_KEY = "ctgu:captcha:1001";

    // http://localhost:8080/opsForValue/session
    // 用户会话管理：用于存储用户的会话信息（如登录令牌或 Session ID），它适合存储单一的、临时的数据项。
    @GetMapping("session")
    public ApiResult session() {
        String sessionId = UUID.randomUUID().toString();
        // 存储用户会话信息并设置过期时间
        redisTemplate.opsForValue().set(SESSION_KEY, sessionId, 30, TimeUnit.MINUTES);
        // 获取会话 ID
        String cachedSession = (String) redisTemplate.opsForValue().get(SESSION_KEY);
        return ApiResult.success("添加 Session ID 成功", cachedSession);
    }

    // http://localhost:8080/opsForValue/captcha
    // 临时验证码：适合存储临时数据，如用户的验证码。
    @GetMapping("captcha")
    public ApiResult captcha() {
        String captchaCode = String.valueOf(ThreadLocalRandom.current().nextInt(100000, 1000000));  // 生成的验证码
        // 存储验证码并设置过期时间
        redisTemplate.opsForValue().set(CAPTCHA_KEY, captchaCode, 5, TimeUnit.MINUTES);
        // 获取验证码
        String cachedCaptcha = (String) redisTemplate.opsForValue().get(CAPTCHA_KEY);
        return ApiResult.success("获取验证码成功", cachedCaptcha);
    }
}